<template>
  <view>
    来到了新增页面

    <!-- 循环渲染商品 -->
    <view v-for="(product, index) in products" :key="index" class="product-item">
      
      <!-- 商品选择 -->
      <view class="dropdown-container">
        <text class="label">物品:</text>
        <van-dropdown-menu>
          <van-dropdown-item 
            v-model="product.goodsId" 
            :options="productOptions" 
            @change="(event) => updateProductDetails(index, event)" 
          />
        </van-dropdown-menu>
      </view>

      <!-- 仓库选择 -->
      <view class="dropdown-container">
        <text class="label">仓库:</text>
        <van-dropdown-menu>
          <van-dropdown-item 
            v-model="product.warehouseCode" 
            :options="warehouseOptions" 
			@change="(event) => updateWarehouseDetails(index, event)" 
          />
        </van-dropdown-menu>
      </view>

      <!-- 数量输入框 -->
      <view class="quantity-container">
        <text class="label">数量:</text>
        <input 
          v-model.number="product.quantity" 
          type="number" 
          class="quantity-input" 
          placeholder="请输入数量" 
        />
      </view>
      
      <!-- 显示单位 -->
      <view class="unit-info">单位: {{ product.unitName }}</view>
      
      <!-- 删除商品按钮 -->
      <van-button round type="danger" @click="removeProduct(index)" class="procurement-add">删除商品</van-button>
    </view>

    <!-- 供应商选择 -->
    <view class="dropdown-container">
      <text class="label">供应商:</text>
      <van-dropdown-menu>
        <van-dropdown-item 
          v-model="supplierId" 
          :options="supplierOptions" 
		  @change="(event) => updateSupplierDetails(event)" 
        />
      </van-dropdown-menu>
    </view>

    <!-- 添加商品按钮 -->
    <view>
      <van-button 
	  class="procurement-add"
        round 
        type="info" 
        @click="addProduct"
      >
        添加商品
      </van-button>
    </view>

    <!-- 确认下单按钮 -->
    <view>
      <van-button 
	  class="procurement-add"
        round 
        type="danger" 
        @click="placeOrder"
		:disabled="isSubmitDisabled"
      >
        确认下单
      </van-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      products: [{ goodsId: '', warehouseCode: '', unitName: '', quantity: 1 }],
      productOptions: [], // 商品选项
      warehouseOptions: [], // 仓库选项
      supplierOptions: [], // 供应商选项
      supplierId: '',
    };
  },
  computed: {
    // 计算是否禁用下单按钮：只有当所有商品信息都填写完整时，才能点击
    isSubmitDisabled() {
      return this.products.some(product => {
        return !product.goodsId || !product.warehouseCode || product.quantity <= 0;
      }) || !this.supplierId;
    }
  },
  created() {
    this.fetchProductOptions();
    this.fetchWarehouseOptions();
    this.fetchSupplierOptions();
  },
  methods: {
    // 添加商品
    addProduct() {
      this.products.push({ goodsId: '', warehouseCode: '', unitName: '', quantity: 1 });
    },
    // 删除商品
    removeProduct(index) {
      this.products.splice(index, 1);
    },
    // 获取商品选项
    fetchProductOptions() {
      const url = this.$C.api_url + 'api/goods';
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'GET',
		header:{
			'satoken':token
		},
        success: (res) => {
          if (res.data.code === 200) {
            this.productOptions = res.data.data.map(item => ({
              text: item.goodsName,
              value: item.goodsCode,
              unitName: item.unitName
            }));
          } else {
            uni.showToast({
              title: '物品获取失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '获取物品失败，请稍后再试',
            icon: 'none'
          });
          console.error('请求失败', err);
        }
      });
    },
    // 获取仓库选项
    fetchWarehouseOptions() {
      const url = this.$C.api_url + 'api/warehouse/minList';
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'GET',
		header:{
			'satoken':token
		},
        success: (res) => {
          if (res.data.code === 200) {
            this.warehouseOptions = res.data.data.map(item => ({
              text: item.warehouseName,
              value: item.warehouseCode
            }));
          } else {
            uni.showToast({
              title: '仓库获取失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '获取仓库失败，请稍后再试',
            icon: 'none'
          });
          console.error('请求失败', err);
        }
      });
    },
    // 获取供应商选项
    fetchSupplierOptions() {
      const url = this.$C.api_url + 'api/minSupplier/list';
	  let token = uni.getStorageSync('token');
      uni.request({
        url,
        method: 'GET',
		header:{
			'satoken':token
		},
        success: (res) => {
          if (res.data.code === 200) {
            this.supplierOptions = res.data.data.map(item => ({
              text: item.supplierName,
              value: item.supplierCode
            }));
          } else {
            uni.showToast({
              title: '供应商获取失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '获取供应商失败，请稍后再试',
            icon: 'none'
          });
          console.error('请求失败', err);
        }
      });
    },
    // 更新商品的详细信息（例如单位）
    updateProductDetails(index, event) {
      const value = event.detail; // 获取选中的 value
      const product = this.productOptions.find(p => String(p.value) === String(value));
      if (product) {
        this.$set(this.products, index, { 
          ...this.products[index], 
          goodsId: value,
          unitName: product.unitName 
        });
      }
    },
	// 给库存赋值
	updateWarehouseDetails(index, event) {
	  const value = event.detail; // 获取选中的 value
	  const product = this.warehouseOptions.find(p => String(p.value) === String(value));
	  if (product) {
	    this.$set(this.products, index, { 
	      ...this.products[index], 
	      warehouseCode: value,
	    });
	  }
	},
	//给供应商赋值
	updateSupplierDetails(event) {
	  const value = event.detail; // 获取选中的 value
	 this.supplierId = value;  // 正确赋值给 supplierId
	},
    // 提交下单操作
    placeOrder() {
		console.log('订单信息：', {
		  products: this.products,
		  supplierId: this.supplierId
		});
		const data = {
		  inventoryList: this.products,
		  supplierId: this.supplierId
		}
      // 在这里可以处理提交订单的逻辑
	  const url = this.$C.api_url + 'api/order/orderAdd';
	  let token = uni.getStorageSync('token');
	  uni.request({
	    url,
	    method: 'POST',
		data : data,
		header:{
			'satoken':token
		},
	    success: (res) => {
	      if (res.data.code === 200) {
			uni.showToast({
			  title: '订单提交成功',
			  icon: 'success'
			});
			
			// 延迟一秒后跳转
			setTimeout(() => {
			  uni.reLaunch({
			    url: '/pages/procurement/procurement', // 指定路径，确保重新加载页面
			    success: function () {
			      console.log('页面已重新加载');
			    }
			  });
			}, 1000); // 延迟 1000 毫秒（1秒）
	      } else {
	        uni.showToast({
	          title: '订单提交失败',
	          icon: 'none'
	        });
	      }
	    },
	    fail: (err) => {
	      uni.showToast({
	        title: '获取供应商失败，请稍后再试',
	        icon: 'none'
	      });
	      console.error('请求失败', err);
	    }
	  });
      
      
      // 在实际应用中可以将数据发送到后台进行处理
    }
  }
};
</script>

<style scoped>
view {
  margin: 10px;
}

/* 下拉框容器 */
.dropdown-container {
  margin-bottom: 10px;
}

/* 数量输入框容器 */
.quantity-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

/* 标签样式 */
.label {
  margin-right: 8px;
  font-size: 14px;
  color: #333;
}

/* 数量输入框 */
.quantity-input {
  width: 120px;
  height: 36px;
  padding: 0 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
  text-align: center;
  background-color: #fff;
}

/* 数量输入框获得焦点时 */
.quantity-input:focus {
  border-color: #007bff;
}

/* 显示单位 */
.unit-info {
  font-size: 14px;
  color: #999;
  margin-top: 6px;
}

/* 商品项容器 */
.product-item {
  background-color: #f0f0f0;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}

van-button {
  margin-top: 10px;
}
.procurement-add {
	display: flex;
  justify-content: center; /* 水平居中 */
}
</style>